package com.gugee.tiktok.data.consumer.blogger.core.main;

import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.tiktok.common.model.mysql.BloggerMain;
import com.gugee.tiktok.common.model.mysql.BloggerRecord;
import com.gugee.tiktok.common.model.dal.blogger.BloggerMainRepository;
import com.gugee.tiktok.common.model.dal.blogger.BloggerRecordRepository;
import com.gugee.tiktok.data.consumer.blogger.config.DataConsumerConfig;
import com.gugee.tiktok.data.consumer.blogger.core.service.AwemeClient;
import com.gugee.tiktok.data.consumer.blogger.core.spider.BloggerSpiderClient;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: luolifeng
 * Date: 2020-10-14 19:33
 */
@Slf4j
@Component
public class SaveBloggerRecordMain {
    @Autowired
    BloggerMainRepository bloggerMainRepository;

    @Autowired
    BloggerRecordRepository bloggerRecordRepository;

    @Autowired
    BloggerSpiderClient bloggerSpiderClient;

    @Autowired
    AwemeClient awemeClient;
    @Autowired
    ScheduleTemplate scheduleTemplate;
    @Autowired
    DataConsumerConfig dataConsumerConfig;
    @Autowired
    BloggerMain.BloggerMainMapper bloggerMainMapper;
    @NacosValue(value="${tiktok.data.threadpools.blogger.saveBloggerRecordParallelism}", autoRefreshed = true)
    int saveBloggerRecordParallelism;
    ForkJoinPool forkJoinPool ;
    @PostConstruct
    public void init() {
        log.info("SaveBloggerRecordMain  init");
        forkJoinPool = ThreadPoolUtils.forkJoinPool(saveBloggerRecordParallelism, "SaveBloggerRecord");
        scheduleTemplate.attach("downloadPics", forkJoinPool);
    }
    public void handle(List<BloggerMain> bloggerMains) throws ExecutionException, InterruptedException {
        int dateCode = Integer.parseInt(DateUtil.format(new Date(),"yyyyMMdd"));
         forkJoinPool.submit(() ->
                 bloggerMains.parallelStream().forEach(bloggerMain -> {
                    try{
                        long start=System.currentTimeMillis();
                        run(bloggerMain,dateCode);
                        if((System.currentTimeMillis()-start)/1000>5) {
                            log.info("*****---->>>>SaveBloggerRecordEvent:[Uid={},use times={}]", bloggerMain.getOUid(), (System.currentTimeMillis() - start) / 1000);
                        }
                    }catch (Exception e){
                        log.error("SaveBloggerRecordError! uid:{}",bloggerMain.getOUid(),e);
                    }
                })
        ).get();

    }
    public void handle(BloggerMain bloggerMain) {
        int dateCode = Integer.parseInt(DateUtil.format(new Date(),"yyyyMMdd"));
        try{
            long start=System.currentTimeMillis();
            run(bloggerMain,dateCode);

        }catch (Exception e){
            log.error("SaveBloggerRecordError! uid:{}",bloggerMain.getOUid(),e);
        }
    }
    public void run (BloggerMain bloggerMain,int dateCode){
        if(bloggerMain.getOUid() == 5831967){
            log.info("................{},进入到打点逻辑!",bloggerMain.getOUid());
        }
        val bloggerRecordOptional = bloggerRecordRepository.findByUidAndDatecode(bloggerMain.getOUid(),dateCode);
        BloggerMain blogger = bloggerMain;
        if(blogger == null){
            return;
        }
        BloggerRecord bloggerRecord;

        if(bloggerRecordOptional.isPresent()){
            bloggerRecord = bloggerRecordOptional.get();
            bloggerRecord.setUpdateBy("SaveBloggerRecord -- Update");
        }else{
            bloggerRecord = new BloggerRecord();
            bloggerRecord.setDatecode(dateCode);
            bloggerRecord.setBloggerId(bloggerMain.getId());
            bloggerRecord.setUid(bloggerMain.getOUid());
            bloggerRecord.setFollowerGrowth(0);
            bloggerRecord.setLikeGrowth(0);
            bloggerRecord.setReviewGrowth(0);
            bloggerRecord.setShareGrowth(0);
            bloggerRecord.setViewGrowth(0);
            bloggerRecord.setCreateBy("SaveBloggerRecord -- Add");
            bloggerRecord.setUpdateBy("SaveBloggerRecord -- Add");
        }
        bloggerRecord.setBloggerType(bloggerMain.getBloggerType());
        bloggerRecord.setAvatar(blogger.getOAvatar168());
        bloggerRecord.setNickname(blogger.getONickname());
        bloggerRecord.setUniqueId(blogger.getOUniqueId());
        bloggerRecord.setScore(bloggerMain.getScore());
        // bloggerRecord.setAwemeCount(blogger.getOAwemeCount());
        bloggerRecord.setFollowerCount(blogger.getOFollowerCount());
        bloggerRecord.setLikeTotalCount(blogger.getOTotalFavorited());


        // 当前90天视频总数据（今天打卡数据）
        val bloggerRecordAwemeExtendDto = awemeClient.getBloggerRecordAwemeExtendDto(blogger.getOUid());
        bloggerRecord.setLikeCount(bloggerRecordAwemeExtendDto.getLikesCount());
        bloggerRecord.setViewCount(bloggerRecordAwemeExtendDto.getViewsCount());
        bloggerRecord.setReviewCount(bloggerRecordAwemeExtendDto.getReviewsCount());
        bloggerRecord.setShareCount(bloggerRecordAwemeExtendDto.getShareCount());
        bloggerRecord.setAwemeCount(bloggerRecordAwemeExtendDto.getAwemeCount());

        LocalDateTime dateTime = DateUtil.parseLocalDateTime(String.valueOf(dateCode),"yyyyMMdd");
        val yesterdayCode = DateUtil.format(dateTime.minusDays(1),"yyyyMMdd");
        val yesterdayBloggerRecordOptional = bloggerRecordRepository.
                findByUidAndDatecode(bloggerMain.getOUid(), Integer.parseInt(yesterdayCode));
        if(yesterdayBloggerRecordOptional.isPresent()){
            bloggerRecord.setFollowerGrowth(bloggerRecord.getFollowerCount() -
                    yesterdayBloggerRecordOptional.get().getFollowerCount());
            bloggerRecord.setLikeTotalCountGrowth(bloggerRecord.getLikeTotalCount()- yesterdayBloggerRecordOptional.get().getLikeTotalCount());

            // 获取91天的数据(今天的数据)
            val curBloggerRecordAwemeExtendDto = awemeClient.getBloggerRecordAwemeExtendDto(blogger.getOUid(),dataConsumerConfig.getLatestDays()+1);

            // 计算增量
            bloggerRecord.setLikeGrowth(curBloggerRecordAwemeExtendDto.getLikesCount() - yesterdayBloggerRecordOptional.get().getLikeCount());
            bloggerRecord.setViewGrowth(curBloggerRecordAwemeExtendDto.getViewsCount() - yesterdayBloggerRecordOptional.get().getViewCount());
            bloggerRecord.setReviewGrowth(curBloggerRecordAwemeExtendDto.getReviewsCount() - yesterdayBloggerRecordOptional.get().getReviewCount());
            bloggerRecord.setShareGrowth(curBloggerRecordAwemeExtendDto.getShareCount() - yesterdayBloggerRecordOptional.get().getShareCount());
        }
        bloggerRecordRepository.save(bloggerRecord);
        if(bloggerMain.getOUid() == 5831967){
            log.info("................{},打点成功!",bloggerMain.getOUid());
        }
    }
}
